package com.ynu.springbootappdemo.common.factory;

import com.ynu.springbootappdemo.model.entity.User;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 用户实体工厂
 * 抽象反射工厂创建实例
 * 根据传入的类型创建不同的用户实体
 * 用户角色由application.properties配置
 * */
@Component
public class UserBeanFactory {

    @Resource
    private Environment env;

    public User getInstance(String type) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //读取application.property的配置信息
        String classPath = env.getProperty("entity.class."+type);
        //反射创建对象
        Class<?> configClz = Class.forName(classPath);
        Constructor<?> constructor = configClz.getConstructor();
        return (User) constructor.newInstance();
    }


}
